import tkinter as tk
from tkinter import ttk
from DRLF import *
import configparser as cp


def gui_window():
    # 点击勾选框触发
    def getselect(item):
        print(item, 'selected')

    # 清空
    def unselectall():
        for index, item in enumerate(work_flow):
            v[index].set('')

    # 全选
    def selectall():
        for index, item in enumerate(work_flow):
            v[index].set(item)

    # 提示信息
    def tips():
        print('当前工作流程可能未被正确定义，建议考虑以下工作流程：')
        print('  --创建工作空间请勾选：S1')
        print('  --生成数据请勾选：S2 -> S3')
        print('  --训练模型请勾选：S4 -> S5 -> S6')
        print('  --模型回测请勾选：S4 -> S5 -> S7 -> S8 -> S9')
        print('  --查看调仓行为数据请勾选：S10')

    # 执行工作流
    def showselect():
        selected = [i.get() for i in v if i.get()]
        if work_flow[0] in selected:
            RLdata.create_work_fold()
        elif work_flow[1] in selected:
            df = RLdata().getData()
            if work_flow[2] in selected:
                df_p = RLdata().processedData()
            else:
                tips()
        elif work_flow[3] in selected:
            train, trade, stock_dimension, state_space = RLdata().splitData()
            if work_flow[4] in selected:
                env_train, env_kwargs = RLenv().getEnv(state_space=state_space, stock_dimension=stock_dimension, train=train)
                if work_flow[5] in selected:
                    RLagent().getAgent(env_train=env_train)
                elif work_flow[6] in selected:
                    e_trade_gym, env_trade, obs_trade = RLtrade().getTrade(trade=trade, env_kwargs=env_kwargs)
                    if (work_flow[7] in selected) & (work_flow[8] in selected):
                        df_actions, df_account_value = RLaction().getAction(e_trade_gym=e_trade_gym)
                        RLbacktest().getBacktest(df_account_value=df_account_value)
                    else:
                        tips()
                else:
                    tips()
            else:
                tips()
        elif work_flow[9] in selected:
            RLplot().plot_main()
        else:
            tips()

    def showupdate():
        path = r'F:\PyProject\RLDemo\doc\update.html'
        webbrowser.open(path)

    def config_change_switch(option: str, state: str):
        config = cp.ConfigParser()
        config.read(filenames='./quick_config.ini', encoding='utf-8')
        config.set('save', option, state)
        with open('./quick_config.ini', 'w') as f:
            config.write(f)

    def click_event1():
        if ck1['text'] == '否':
            ck1['text'] = '是'
            config_change_switch(option='save_data', state='True')
        else:
            ck1['text'] = '否'
            config_change_switch(option='save_data', state='False')
        print(ck1['text'])

    def click_event2():
        if ck2['text'] == '否':
            ck2['text'] = '是'
            config_change_switch(option='save_processed_data', state='True')
        else:
            ck2['text'] = '否'
            config_change_switch(option='save_processed_data', state='False')
        print(ck2['text'])

    def click_event3():
        if ck3['text'] == '否':
            ck3['text'] = '是'
            config_change_switch(option='save_model', state='True')
        else:
            ck3['text'] = '否'
            config_change_switch(option='save_model', state='False')
        print(ck3['text'])

    def click_event4():
        if ck4['text'] == '否':
            ck4['text'] = '是'
            config_change_switch(option='save_actions', state='True')
        else:
            ck4['text'] = '否'
            config_change_switch(option='save_actions', state='False')
        print(ck4['text'])

    def click_event5():
        if ck5['text'] == '否':
            ck5['text'] = '是'
            config_change_switch(option='save_account', state='True')
        else:
            ck5['text'] = '否'
            config_change_switch(option='save_account', state='False')
        print(ck5['text'])

    def click_event6():
        if ck6['text'] == '否':
            ck6['text'] = '是'
            config_change_switch(option='save_backtest_result', state='True')
        else:
            ck6['text'] = '否'
            config_change_switch(option='save_backtest_result', state='False')
        print(ck6['text'])

    window = tk.Tk()
    window.geometry('570x190+800+400')
    window.title('DRLF—GUI')
    window.resizable(False, False)
    frame1 = tk.Frame(window, pady=15, padx=15)
    frame1.grid(row=0, column=0)
    # 全选反选
    opt = tk.IntVar()
    ttk.Radiobutton(frame1, text='全选', variable=opt, value=1, command=selectall).grid(row=0, column=0, sticky='w')
    ttk.Radiobutton(frame1, text='清空', variable=opt, value=0, command=unselectall).grid(row=0, column=1, sticky='w')
    ttk.Button(frame1, text="查看开发记录 ", command=showupdate).grid(row=0, column=4)
    work_flow = ['S1-创建工作目录', 'S2-获取数据', 'S3-数据治理', 'S4-切分数据集', 'S5-定义环境', 'S6-定义智能体', 'S7-定义交易', 'S8-定义行动', 'S9-运行回测', 'S10-绘图']
    v = []
    # 设置勾选框，每四个换行
    r_index = 4
    for index, item in enumerate(work_flow):
        v.append(tk.StringVar())
        ttk.Checkbutton(frame1, text=item, variable=v[-1], onvalue=item, offvalue='', command=lambda item=item: getselect(item)).grid(row=index // 5 + 1, column=index % 5, sticky='w')
    ttk.Button(frame1, text="执行该工作流", command=showselect).grid(row=r_index + 2, column=4)

    lab = tk.Label(frame1, text='是否保存下载数据？')
    lab.grid(row=r_index + 1, column=0, sticky=tk.W)
    ck1 = tk.Checkbutton(frame1, text='否', onvalue='是', offvalue='否', command=click_event1)
    ck1.grid(row=r_index + 1, column=1, sticky=tk.W)
    lab = tk.Label(frame1, text='是否保存处理后数据？')
    lab.grid(row=r_index + 1, column=2, sticky=tk.W)
    ck2 = tk.Checkbutton(frame1, text='否', onvalue='是', offvalue='否', command=click_event2)
    ck2.grid(row=r_index + 1, column=3, sticky=tk.W)
    lab = tk.Label(frame1, text='是否保存预训练模型？')
    lab.grid(row=r_index + 2, column=0, sticky=tk.W)
    ck3 = tk.Checkbutton(frame1, text='否', onvalue='是', offvalue='否', command=click_event3)
    ck3.grid(row=r_index + 2, column=1, sticky=tk.W)
    lab = tk.Label(frame1, text='是否保存决策数据？')
    lab.grid(row=r_index + 2, column=2, sticky=tk.W)
    ck4 = tk.Checkbutton(frame1, text='否', onvalue='是', offvalue='否', command=click_event4)
    ck4.grid(row=r_index + 2, column=3, sticky=tk.W)
    lab = tk.Label(frame1, text='是否保存每日账户数据？')
    lab.grid(row=r_index + 3, column=0, sticky=tk.W)
    ck5 = tk.Checkbutton(frame1, text='否', onvalue='是', offvalue='否', command=click_event5)
    ck5.grid(row=r_index + 3, column=1, sticky=tk.W)
    lab = tk.Label(frame1, text='是否保存回测结果？')
    lab.grid(row=r_index + 3, column=2, sticky=tk.W)
    ck6 = tk.Checkbutton(frame1, text='否', onvalue='是', offvalue='否', command=click_event6)
    ck6.grid(row=r_index + 3, column=3, sticky=tk.W)

    window.mainloop()


if __name__ == '__main__':
    gui_window()
